<?php

namespace Wxwork\Common;

class XMLParse
{

    /**
     * 解析xml
     * @param string $xml
     * @return array
     */
    public static function xmlToArr(string $xml): array
    {
        $obj = simplexml_load_string($xml);
        if (!$obj) {
            return [];
        }

        return self::objectToArray($obj);
    }

    private static function objectToArray($object)
    {
        if (count($object) == 0) return trim((string)$object);
        $result = array();
        $object = is_object($object) ? get_object_vars($object) : $object;
        foreach ($object as $key => $val) {
            $val = (is_object($val) || is_array($val)) ? self::objectToArray($val) : $val;
            $result[$key] = $val;
        }
        return $result;
    }

    /**
     * 生成xml消息
     * @param string $encrypt 加密后的消息密文
     * @param string $signature 安全签名
     * @param string $timestamp 时间戳
     * @param string $nonce 随机字符串
     */
    public function generate($encrypt, $signature, $timestamp, $nonce)
    {
        $format = "<xml>
<Encrypt><![CDATA[%s]]></Encrypt>
<MsgSignature><![CDATA[%s]]></MsgSignature>
<TimeStamp>%s</TimeStamp>
<Nonce><![CDATA[%s]]></Nonce>
</xml>";
        return sprintf($format, $encrypt, $signature, $timestamp, $nonce);
    }

}
